﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;

using Microsoft.Practices.Unity.Configuration;

namespace WFL.IoCUnity
{
    [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class
        , AllowMultiple = false
        , Inherited = true)]
    public class UnityConfigurationAttribute : Attribute
    {
        public string File { get; set; }
        public string Container { get; set; }

        public UnityConfigurationSection GetUnityConfigurationSection()
        {
            if (!string.IsNullOrEmpty(this.File))
            {
                var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.File) };
                Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                return configuration == null ? null : configuration.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
            }
            return ConfigurationManager.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            else
            {
                UnityConfigurationAttribute attr = (UnityConfigurationAttribute)obj;
                string file1 = File == "" ? null : File;
                string container1 = Container == "" ? null : Container;
                string file2 = File == "" ? null : File;
                string container2 = Container == "" ? null : Container;
                return file1 == file2 && container1 == container2;
            }
        }

        public override int GetHashCode()
        {
            return ((string.IsNullOrEmpty(File) ? "|" : File) + Container).GetHashCode();
        }
    }
}
